<template>
    <div class="mod-config">
        
<el-form :inline="true" :model="dataForm" @keyup.enter.native="queryByCriteria">
    <el-form-item prop="selectedOptions" style="float: left;">
        <el-input v-model="filepath" class="filepath-input" placeholder="/" disabled style="width: 400px;">
            <template slot="prepend">文件目录:</template>
</el-input>
<el-button v-show="this.filePathDirList.length != 1" icon="el-icon-back" @click="backDir">返回上一级</el-button>
<el-button type="" @click="createDir">创建文件夹</el-button>
<el-button type="" @click="openUploadDialog">发布资源</el-button>
<el-button type="danger" v-show="showMoveBtn" @click="multipledeleteHandle">批量删除</el-button>
</el-form-item>
<el-form-item style="float: right;">
    <el-button @click="queryByCriteria(serchInput,dataForm.status)">查询</el-button>
</el-form-item>
<el-form-item style="float: right;">
    <el-input v-model="serchInput" placeholder="请输入文件名或目录名" clearable></el-input>
</el-form-item>
<el-form-item prop="selectedOptions" style="float: right;">
    <el-cascader v-model="selectedOptions" size="large" :options="options" :props="{ expandTrigger: 'hover',checkStrictly: false }" @change="handleCityChange" clearable/>
</el-form-item>

</el-form>
<el-table :data="dataList" stripe v-loading="dataListLoading" style="width: 100%" @selection-change="handleSelectionChange">
    <el-table-column prop="" type="selection" />

    <el-table-column prop="fileName" label="文件名" show-overflow-tooltip>
        <el-tooltip placement="top" slot-scope="scope" v-if="scope.row.fileType==1">
            <div slot="content">文件夹名称：{{scope.row.fileName}}<br/>发布者：{{scope.row.teacherName}}<br/>下载数：{{scope.row.fileLoaddownCount}}<br/></div>
            <div>
                <el-image style="width: 30px; height: 30px;vertical-align: middle;" :src="require(scope.row.fileType==0?'../../../assets/img/filepacks.png':'../../../assets/img/file.png')" />
                <span class="filename-span" :class="scope.row.fileType==0?'isDir':''" @click="clickFandP(scope.row)">{{ scope.row.fileName }}</span>
            </div>
        </el-tooltip>
        <div slot-scope="scope" v-else-if="scope.row.fileType==0">
            <el-image style="width: 30px; height: 30px;vertical-align: middle;" :src="require(scope.row.fileType==0?'../../../assets/img/filepacks.png':'../../../assets/img/file.png')" />
            <span class="filename-span" :class="scope.row.fileType==0?'isDir':''" @click="clickFandP(scope.row)">{{ scope.row.fileName }}</span>
        </div>
    </el-table-column>
    <el-table-column prop="createTime" label="创建时间"> </el-table-column>
    <el-table-column prop="fileSize" label="大小"> </el-table-column>
    <!-- <el-table-column prop="teacherName" label="发布者"> </el-table-column>
    <el-table-column prop="fileLoaddownCount" label="下载次数"> </el-table-column> -->
    <el-table-column fixed="right" header-align="center" align="center" width="250" label="操作">
        <template slot-scope="scope">
            <el-button
            type="text"
            size="small"
             @click="openPathDialog(scope.row.id)">
             移动
            </el-button>
            <el-button
            type="text"
            size="small"
            @click="modifyName(scope.row)"
            >修改</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="viewFile(scope.row)"
              v-if="scope.row.fileType==1"
              >查看</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="deleteHandle(scope.row)"
              >删除</el-button
            >
          </template>
    </el-table-column>
</el-table>

<!-- 分页条 -->
<el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage" layout="total, sizes, prev, pager, next, jumper">
</el-pagination>
<!-- 展示文件框 暂时只能预览pdf 暂作注释处理 -->
<!-- <el-dialog title="提示" :visible.sync="viewFileDialogVisible" fullscreen center destroy-on-close>
    <embed type="text/html" :src="fileSrc" width="100%" height="900px">
    <span slot="footer" class="dialog-footer">
  </span>
</el-dialog> -->

<!-- 发布资源模态框 -->
<el-dialog title="发布公共资源" :visible.sync="dialogUploadVisible" width="600px" :destroy-on-close="true" @close="resetForm('uploadForm')">
    <el-form ref="uploadForm" v-loading="dataListLoading" :model="uploadForm" label-width="120px" :rules="rules" class="demo-ruleForm" element-loading-text="文件上传中">
        <el-form-item label="教师名称" label-width="120px" prop="name">
            <el-input v-model="uploadForm.name" style="width:360px" />
        </el-form-item>
        <el-form-item label="省区城市" prop="selectedOptions" label-width="120px">
            <el-cascader v-model="uploadForm.selectedOptions" size="large" :options="uploadCityOptions" style="width: 360px;" />
        </el-form-item>
        <el-form-item label="单位名称" prop="unit" label-width="120px">
            <el-input v-model="uploadForm.unit" style="width:360px" />
        </el-form-item>
        <el-form-item label="联系方式" prop="phone" label-width="120px">
            <el-input v-model="uploadForm.phone" style="width:360px" />
        </el-form-item>
        <el-form-item label="教参文件" prop="file" label-width="120px">
            <el-upload ref="uploadbox" class="upload-demo" drag :on-change="uploadChange" :limit="1" :on-exceed="handleExceed" :before-upload="beforeAvatarUpload" action="http://121.41.167.195:8000/api/oss/upload" multiple>
                <i class="el-icon-upload" />
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div slot="tip" class="el-upload__tip">只能上传pdf、doc 、docx、ppt和pptx格式文件，且不超过10MB</div>
            </el-upload>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm('uploadForm')">发布公共资源</el-button>
            <el-button @click="resetForm('uploadForm')">清空文件</el-button>
        </el-form-item>
    </el-form>
</el-dialog>
<!-- 移动文件夹模态框 -->
<el-dialog title="移动到" :visible.sync="dialogPathVisible" width="600px" destroy-on-close>
    <el-tree ref="tree" :props="props" :load="loadNode" lazy node-key="id" :expand-on-click-node="false" :render-after-expand="false" @node-click="spanDirclick" show-radiobox highlight-current>
        <span slot-scope="{ node }" class="custom-tree-node">
          <el-image style="width: 20px;vertical-align: middle;" :src="require('../../../assets/img/filepacks.png')" />
          <span class="spanDir" >   {{ node.label }}</span>
        </span>
    </el-tree>
    <div slot="footer" class="dialog-footer">
        <el-button @click="movedialogCancel()">取 消</el-button>
        <el-button type="primary" :disabled="isMoveVisableBtn" @click="doMove()">移动到此处</el-button>
    </div>
</el-dialog>
</div>
</template>

<script>
    import {
        regionDataPlus,
    } from 'element-china-area-data'
    export default {
        data() {
            return {
                cityInfo: {
                    pcatype: '',
                    pcaid: ''
                },
                dataForm: {
                    status: '',

                },
                uploadForm: {
                    id: '',
                    name: '',
                    selectedOptions: [],
                    unit: '',
                    phone: '',
                    file: ''
                },
                props: {
                    label: 'name',
                    children: '',
                    isLeaf: 'leaf'
                },
                rules: {
                    name: [{
                        required: true,
                        message: '请输入教师名称',
                        trigger: 'blur'
                    }, {
                        min: 2,
                        max: 10,
                        message: '长度在 2 到 10 个字符',
                        trigger: 'blur'
                    }],
                    selectedOptions: [{
                        required: true,
                        message: '请选择好省市区县',
                        trigger: 'change'
                    }],
                    unit: [{
                        required: true,
                        message: '请输入单位名称',
                        trigger: 'change'
                    }],
                    file: [{
                        required: true,
                        message: '请上传文件',
                        trigger: 'change'
                    }],
                    phone: [{
                        required: true,
                        message: '请输入联系方式',
                        trigger: 'change'
                    }]
                },
                serchInput: '',
                viewFileDialogVisible: false,
                upperFid: 0,
                fileSrc: '',
                dataList: [],
                pageIndex: 1,
                pageSize: 10,
                totalPage: 0,
                dataListLoading: false,
                selectedOptions: [],
                options: regionDataPlus,
                uploadCityOptions: regionDataPlus,
                multipleSelection: [],
                showMoveBtn: false,
                filePathDirList: [0],
                filePathDirNameList: [],
                dialogPathVisible: false,
                isMoveVisableBtn: false,
                selectMoveId: '',
                dialogUploadVisible: false,
            };
        },
        components: {},
        created() {
            this.getPublicFile();
        },
        watch: {
            // 当前目录id改变 更新列表
            upperFid: {
                handler(newValue, OldValue) {
                    this.getPublicFile()
                }
            },
            // 只要更新文件目录的id列表 就将最新的最后一个id赋值给当前currentDirFid
            filePathDirList: {
                handler(newValue) {
                    this.upperFid = newValue[newValue.length - 1]
                }
            }
        },
        computed: {
            // 路径展示由当前存储的目录数组拼接而成
            filepath: function() {
                if (this.filePathDirNameList.length == 0) {
                    return '/根目录'
                } else {
                    return '/根目录/' + this.filePathDirNameList.join('/')
                }
            }
        },
        methods: {
            // 点击选中要移动的文件夹
            spanDirclick() {
                this.isMoveVisableBtn = false
            },
            // 根据当前查询条件查询
            queryByCriteria() {
                this.pageIndex = 1
                this.dataListLoading = true
                this.$http({
                    url: this.$http.adornUrl("/publicResource/getPublicFile"),
                    method: "get",
                    params: this.$http.adornParams({
                        upperFid: this.upperFid,
                        fileName: this.serchInput,
                        page: this.pageIndex,
                        limit: this.pageSize,
                        pcatype: this.cityInfo.pcatype,
                        pcaid: this.cityInfo.pcaid
                    })
                }).then(({
                    data
                }) => {
                    if (data && data.code === 0) {
                        this.dataList = data.data.records;
                        this.totalPage = data.data.total;
                    } else {
                        this.dataList = [];
                        this.totalPage = 0;
                    }
                    this.dataListLoading = false;
                });
            },
            // 根据条件查找当前目录文件的接口
            getPublicFile() {
                this.dataListLoading = true
                this.$http({
                    url: this.$http.adornUrl("/publicResource/getPublicFile"),
                    method: "get",
                    params: this.$http.adornParams({
                        upperFid: this.upperFid,
                        fileName: this.serchInput,
                        page: this.pageIndex,
                        limit: this.pageSize,
                        pcatype: this.cityInfo.pcatype,
                        pcaid: this.cityInfo.pcaid
                    })
                }).then(({
                    data
                }) => {
                    if (data && data.code === 0) {
                        this.dataList = data.data.records;
                        this.totalPage = data.data.total;
                    } else {
                        this.dataList = [];
                        this.totalPage = 0;
                    }
                    this.dataListLoading = false;
                });
            },
            // 每页数
            sizeChangeHandle(val) {
                this.pageSize = val;
                this.pageIndex = 1;
                this.getPublicFile()
            },
            // 当前页
            currentChangeHandle(val) {
                this.pageIndex = val;
                this.getPublicFile()
            },
            // 删除
            deleteHandle(row) {
                this.$confirm(`确定对[${row.fileName}]进行[删除]操作?`, "提示", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning",
                    })
                    .then(() => {
                        this.dataListLoading = true
                        this.$http({
                            url: this.$http.adornUrl("/publicResource/deleteFile"),
                            method: "post",
                            data: this.$http.adornData([row.id], false),
                        }).then(({
                            data
                        }) => {
                            if (data && data.code === 0) {
                                this.$message({
                                    message: "删除成功",
                                    type: "success",
                                    duration: 1500,
                                    onClose: () => {
                                        this.getPublicFile()
                                    },
                                });
                            } else {
                                this.dataListLoading = false
                                this.$message.error(data.msg);
                            }
                        });
                    })
                    .catch(() => {});
            },
            // 查看文档
            viewFile(row) {
                const elemtA = document.createElement('a')
                elemtA.setAttribute('href', row.fileAddress)
                elemtA.setAttribute('target', '"_blank"')
                elemtA.download = row.fileName
                    // const event = new MouseEvent('click')
                elemtA.click()

            },
            // 点击多选框事件
            handleSelectionChange(val) {
                this.showMoveBtn = val.length != 0
                this.multipleSelection = val
            },
            // 删除多个文件
            multipledeleteHandle() {
                const ids = []
                this.multipleSelection.forEach(item => {
                    ids.push(item.id)
                })
                this.$confirm(`确定对这些文件进行[删除]操作?`, "提示", {
                        confirmButtonText: "确定",
                        cancelButtonText: "取消",
                        type: "warning",
                    })
                    .then(() => {
                        this.$http({
                            url: this.$http.adornUrl("/publicResource/deleteFile"),
                            method: "post",
                            data: this.$http.adornData(ids, false),
                        }).then(({
                            data
                        }) => {
                            if (data && data.code === 0) {
                                this.$message({
                                    message: "删除成功",
                                    type: "success",
                                    duration: 1500,
                                    onClose: () => {
                                        this.getPublicFile()
                                    },
                                });
                            } else {
                                this.$message.error(data.msg);
                            }
                        });
                    })
                    .catch(() => {});
            },
            // 修改名称
            modifyName(row) {
                this.$prompt('请输入修改名称', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消'
                }).then(({
                    value
                }) => {
                    const typeArray = row.fileName.split('.')
                    const currentName = row.fileType == 0 ? value : value + '.' + typeArray[typeArray.length - 1]
                    this.$http({
                        url: this.$http.adornUrl("/publicResource/updateFile"),
                        method: "post",
                        data: this.$http.adornData({
                            fileName: currentName,
                            id: row.id
                        }, false),
                    }).then(({
                        data
                    }) => {
                        if (data && data.code === 0) {
                            this.$message({
                                message: "修改成功",
                                type: "success",
                                duration: 1500,
                                onClose: () => {
                                    this.getPublicFile()
                                },
                            });
                        } else {
                            this.$message.error(data.msg);
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '取消修改'
                    })
                })
            },
            // 创建文件夹
            createDir() {
                this.$prompt('请输入文件夹名称', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消'
                }).then(({
                    value
                }) => {
                    this.$http({
                        url: this.$http.adornUrl("/publicResource/uploadFileToPublic"),
                        method: "post",
                        data: this.$http.adornData({
                            fileName: value,
                            fileType: 0,
                            upperFid: this.upperFid
                        }, false),
                    }).then(({
                        data
                    }) => {
                        if (data && data.code === 0) {
                            this.$message({
                                message: "创建成功",
                                type: "success",
                                duration: 1500,
                                onClose: () => {
                                    this.getPublicFile()
                                },
                            });
                        } else {
                            this.$message.error(data.msg);
                        }
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '取消创建'
                    })
                })
            },
            // 点击城市事件
            handleCityChange(value) {
                let len = value.length
                    // 如果长度为0 说明清空了城市条件，如果不为就提取城市的信息id
                if (value != 0) {
                    // 如果最后一位是空的  那么就拿前一位的值
                    if (value[len - 1] == '') {
                        // 如果最后一位是空的 那么就取前一个值
                        if (len == 1) {
                            Object.assign(this.$data.cityInfo, this.$options.data().cityInfo)
                        } else {
                            this.cityInfo.pcatype = len - 2
                            this.cityInfo.pcaid = value[len - 2]
                        }

                    } else {
                        // 如果最后一位不是空的  那么就直接取最后一个
                        this.cityInfo.pcatype = len - 1
                        this.cityInfo.pcaid = value[len - 1]
                    }
                } else {
                    Object.assign(this.$data.cityInfo, this.$options.data().cityInfo)
                }
                this.queryByCriteria()
            },
            // 点击文件或文件夹事件
            clickFandP(row) {
                if (row.fileType == 0) {
                    this.filePathDirList.push(row.id)
                    this.filePathDirNameList.push(row.fileName)
                }
            },
            // 回退
            backDir() {
                this.filePathDirList.pop()
                this.filePathDirNameList.pop()
            },
            // 打开移动文件夹窗口
            openPathDialog(id) {
                this.isMoveVisableBtn = true
                this.dialogPathVisible = true
                this.selectMoveId = id
            },
            // 加载节点
            loadNode(node, resolve) {
                const nowId = this.selectMoveId

                if (node.level == 0) {
                    return resolve([{
                        name: '/根目录',
                        id: 0
                    }])
                } else {
                    this.getDirList(nowId, node.data.id, resolve)
                        // this.getDirList(node.data.id, resolve)
                }
                if (node.level === 0) {
                    this.getDirList(nowId, 0, resolve)
                        // this.getDirList(0, resolve)
                } else {
                    this.getDirList(nowId, node.data.id, resolve)
                        // this.getDirList(node.data.id, resolve)
                }
            },
            // 获取当前目录的文件夹
            getDirList(mfid, fid, resolve) {
                this.$http({
                    url: this.$http.adornUrl("/publicResource/getDirectory"),
                    method: "get",
                    params: this.$http.adornParams({
                        mFid: mfid,
                        upperFid: fid
                    }),
                }).then(({
                    data
                }) => {
                    if (data && data.code === 0) {
                        const arrs = data.data.map(item => {
                            return {
                                name: item.fileName,
                                id: item.id,
                                upperFid: item.upperFid
                            }
                        })
                        return resolve(arrs)
                    } else {
                        this.$message.error(data.msg);
                    }
                });
            },
            // 移动操作
            doMove() {
                this.dialogPathVisible = false
                this.$http({
                    url: this.$http.adornUrl("/publicResource/updateFile"),
                    method: "post",
                    data: this.$http.adornData({
                        upperFid: this.$refs.tree.getCurrentNode().id,
                        id: this.selectMoveId
                    }, false),
                }).then(({
                    data
                }) => {
                    if (data && data.code === 0) {
                        this.$message({
                            message: "修改成功",
                            type: "success",
                            duration: 1500,
                            onClose: () => {
                                this.getPublicFile()
                            },
                        });
                    } else {
                        this.$message.error(data.msg);
                    }
                });
            },
            // 关闭移动文件夹窗口
            movedialogCancel() {
                this.dialogPathVisible = false
            },
            // 打开发布模态框
            openUploadDialog() {
                this.dialogUploadVisible = true
            },
            // 点击提交发布
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.dataListLoading = true
                        this.$http({
                            url: this.$http.adornUrl("/publicResource/uploadFileToPublic"),
                            method: "post",
                            data: {
                                fileAddress: this.uploadForm.file.response.url,
                                fileType: 1,
                                fileSize: this.uploadForm.file.size,
                                fileName: this.uploadForm.file.raw.name,
                                phone: this.uploadForm.phone,
                                teacherName: this.uploadForm.name,
                                unitName: this.uploadForm.unit,
                                pid: this.uploadForm.selectedOptions[0] || '',
                                cid: this.uploadForm.selectedOptions[1] || '',
                                aid: this.uploadForm.selectedOptions[2] || '',
                                fileBelongto: 0,
                                upperFid: this.upperFid,
                                verifyState: 1,
                                fileLoaddownCount: 0
                            }
                        }).then(({
                            data
                        }) => {
                            if (data && data.code === 0) {
                                this.dataListLoading = false
                                this.$message({
                                    message: "发布公共资源成功",
                                    type: "success",
                                    duration: 1500,
                                    onClose: () => {
                                        this.getPublicFile()
                                        this.dialogUploadVisible = false
                                        this.resetForm(formName)
                                    },
                                });
                            } else {
                                this.$message.error(data.msg);
                            }
                        });
                    } else {
                        this.dataListLoading = false
                        console.log('error submit!!')
                        return false
                    }
                })
            },
            // 超出文件数量提示
            handleExceed(files, fileList) {
                this.$message.warning(`当前发布文件数量超出`)
            },
            // 上传之前钩子
            beforeAvatarUpload(file) {
                this.dataListLoading = true
                if (file.name.length >= 50) {
                    this.$message.error('文件名过长，请修改!')
                    this.dataListLoading = false
                    return false
                }
                const filesname = file.name.split('.')
                const type = filesname.slice(-1)[0]
                if (type) {
                    const isFile = type == 'pdf' || type == 'doc' || type == 'docx' || type == 'ppt' || type == 'pptx'
                    const isLt2M = file.size / 1024 / 1024 < 10

                    if (!isFile) {
                        this.$message.error('上传文件只能是 pdf、doc 、docx、ppt和pptx格式!')
                        this.dataListLoading = false
                    }
                    if (!isLt2M) {
                        this.$message.error('上传文件大小不能超过 10MB!')
                        this.dataListLoading = false
                    }
                    return isFile && isLt2M
                }
            },
            // 上传成功后的钩子
            uploadChange(file, fileList) {
                if (file.status == 'success') {
                    this.uploadForm.file = file
                    console.log(this.uploadForm.file)
                    this.dataListLoading = false
                }
            },
            // 重置表单
            resetForm(formName) {
                this.$refs.uploadbox.clearFiles()
                this.$refs[formName].resetFields()
                Object.assign(this.$data.uploadForm, this.$options.data().uploadForm)
            },
        },
    };
</script>
<style lang="less" scoped>
    .filename-span {
        vertical-align: middle;
        margin: 0 2px;
    }
    
    .isDir {
        cursor: pointer;
        line-height: 30px;
        &:hover {
            text-decoration: underline;
        }
    }
    
    .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
        width: 100%;
        .spanDir {
            width: 100%;
            color: #06a7ff;
        }
    }
    
    .spanDir {
        width: 100%;
    }
    
    .el-tree-node__content {
        width: 100%;
        &:hover {
            .spanDir {
                width: 100%;
                color: #06a7ff;
            }
        }
    }
</style>